/**
 * 批改结果状态管理 Store
 * 管理批改结果、加载状态和批改历史
 */

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import * as correctionApi from '../services/correctionApi.js';

export const useCorrectionStore = defineStore('correction', () => {
  // ==================== 辅助函数 ====================

  /**
   * 带指数退避的重试机制
   * @param {Function} fn - 要执行的异步函数
   * @param {number} maxRetries - 最大重试次数（默认3次）
   * @param {number} initialDelay - 初始延迟时间（毫秒，默认1000ms）
   * @returns {Promise} 函数执行结果
   */
  const retryWithBackoff = async (fn, maxRetries = 3, initialDelay = 1000) => {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      try {
        return await fn();
      } catch (error) {
        // 判断是否应该重试
        const isRetryableError = 
          error.type === 'NOT_FOUND' || 
          error.type === 'PROCESSING' ||  // 批改进行中，应该重试
          error.status === 404 ||
          error.status === 'processing' ||
          error.type === 'NETWORK_ERROR' ||
          error.message?.includes('网络') ||
          error.message?.includes('超时');
        
        const isLastAttempt = attempt === maxRetries - 1;
        
        // 如果不应该重试，或者已经是最后一次尝试，直接抛出错误
        if (!isRetryableError || isLastAttempt) {
          console.log(`[CorrectionStore] Retry failed at attempt ${attempt + 1}/${maxRetries}`, error.type);
          throw error;
        }
        
        // 指数退避：1秒、2秒、4秒
        const delay = initialDelay * Math.pow(2, attempt);
        console.log(`[CorrectionStore] Retrying after ${delay}ms (attempt ${attempt + 1}/${maxRetries}), reason:`, error.type || error.message);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  };

  // ==================== 状态 ====================

  /**
   * 当前批改结果
   */
  const correctionResult = ref(null);

  /**
   * 批改历史列表
   */
  const history = ref([]);

  /**
   * 加载状态
   */
  const loading = ref(false);

  /**
   * 错误信息
   */
  const error = ref(null);

  /**
   * 批改进度（用于显示批改过程）
   * 0-100的数字，表示批改进度百分比
   */
  const progress = ref(0);

  /**
   * 批改状态
   * idle: 空闲, submitting: 提交中, processing: 批改中, completed: 完成, failed: 失败
   */
  const status = ref('idle');

  // ==================== 计算属性 ====================

  /**
   * 是否正在批改
   */
  const isProcessing = computed(() => {
    return status.value === 'submitting' || status.value === 'processing';
  });

  /**
   * 是否有批改结果
   */
  const hasResult = computed(() => !!correctionResult.value);

  /**
   * 当前批改的分数
   */
  const currentScore = computed(() => {
    return correctionResult.value?.score_breakdown?.total_score || null;
  });

  /**
   * 批改错误数量
   */
  const errorCount = computed(() => {
    return correctionResult.value?.corrections?.length || 0;
  });

  /**
   * 错误分类统计
   */
  const errorCategories = computed(() => {
    if (!correctionResult.value?.corrections) {
      return {};
    }

    const categories = {};
    correctionResult.value.corrections.forEach((correction) => {
      const type = correction.type || 'other';
      categories[type] = (categories[type] || 0) + 1;
    });

    return categories;
  });

  /**
   * 批改历史数量
   */
  const historyCount = computed(() => history.value.length);

  // ==================== 操作 ====================

  /**
   * 提交作文进行批改
   * @param {string} essayId - 作文ID
   * @returns {Promise<Object>} 批改结果
   */
  const submitForCorrection = async (essayId) => {
    loading.value = true;
    error.value = null;
    status.value = 'submitting';
    progress.value = 0;

    try {
      console.log('[CorrectionStore] Submit for correction:', essayId);

      // 开始批改过程，显示进度
      status.value = 'processing';
      
      // 模拟进度更新（因为真实API可能较慢，提供用户反馈）
      const progressInterval = setInterval(() => {
        if (progress.value < 90) {
          progress.value += 10;
        }
      }, 500);

      // 调用真实API
      const response = await correctionApi.submitForCorrection(essayId);
      
      // 后端返回格式：{ success, data, message }，其中data包含essayId等字段
      const result = response.data;
      
      // 添加详细日志以便调试
      console.log('[CorrectionStore] API Response:', {
        hasResult: !!result,
        hasEssayId: !!result?.essayId,
        hasId: !!result?.id,
        status: result?.status,
        hasCorrectionResult: !!result?.correctionResult
      });

      // 验证返回数据（兼容id和essayId两种字段名）
      if (!result || (!result.essayId && !result.id)) {
        console.error('[CorrectionStore] Invalid response data:', result);
        throw new Error('服务器返回的批改数据格式不正确');
      }

      // 完成进度
      clearInterval(progressInterval);
      progress.value = 100;

      // 保存批改结果
      correctionResult.value = result.correctionResult;
      status.value = 'completed';

      console.log('[CorrectionStore] Correction completed:', result.essayId || result.id);
      return { success: true, data: result };
    } catch (err) {
      const errorMessage = err.message || '批改失败';
      error.value = errorMessage;
      status.value = 'failed';
      console.error('[CorrectionStore] Submit correction failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取批改结果（带重试机制）
   * @param {string} essayId - 作文ID
   * @param {boolean} useRetry - 是否使用重试机制（默认true）
   * @returns {Promise<Object>} 批改结果
   */
  const getCorrectionResult = async (essayId, useRetry = true) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[CorrectionStore] Get correction result:', essayId, 'useRetry:', useRetry);

      // 定义API调用函数
      const fetchResult = async () => {
        const response = await correctionApi.getCorrectionResult(essayId);
        
        // 后端返回格式：{ success, data, message }，其中data包含essayId等字段
        const result = response.data;
        
        // 添加详细日志以便调试
        console.log('[CorrectionStore] API Response:', {
          hasResult: !!result,
          hasEssayId: !!result?.essayId,
          hasId: !!result?.id,
          status: result?.status,
          hasCorrectionResult: !!result?.correctionResult
        });

        // 验证返回数据（兼容id和essayId两种字段名）
        if (!result || (!result.essayId && !result.id)) {
          console.error('[CorrectionStore] Invalid response data:', result);
          throw new Error('服务器返回的批改数据格式不正确');
        }

        // 如果状态是processing，抛出特殊错误以触发重试
        if (result.status === 'processing') {
          const processingError = new Error('批改正在进行中');
          processingError.type = 'PROCESSING';
          processingError.status = 'processing';
          throw processingError;
        }

        return result;
      };

      // 根据参数决定是否使用重试机制
      const result = useRetry 
        ? await retryWithBackoff(fetchResult, 3, 1000)
        : await fetchResult();

      // 保存批改结果
      correctionResult.value = result.correctionResult;

      console.log('[CorrectionStore] Got correction result for essay:', result.essayId || result.id);
      return { success: true, data: result };
    } catch (err) {
      const errorMessage = err.message || '获取批改结果失败';
      error.value = errorMessage;
      console.error('[CorrectionStore] Get correction result failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取批改历史列表
   * @param {Object} filters - 过滤条件
   * @param {number} filters.limit - 每页数量
   * @param {number} filters.offset - 偏移量
   * @param {string} filters.gradeLevel - 学段过滤
   * @returns {Promise<Object>} 批改历史列表
   */
  const fetchHistory = async (filters = {}) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[CorrectionStore] Fetch history:', filters);

      // 调用真实API
      const response = await correctionApi.getHistory(filters);
      const { corrections, pagination } = response.data;

      // 保存历史记录
      history.value = corrections;

      console.log('[CorrectionStore] Fetched', corrections.length, 'history items');
      return {
        success: true,
        data: {
          corrections,
          pagination,
        },
      };
    } catch (err) {
      const errorMessage = err.message || '获取批改历史失败';
      error.value = errorMessage;
      console.error('[CorrectionStore] Fetch history failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 清空当前批改结果
   */
  const clearResult = () => {
    correctionResult.value = null;
    progress.value = 0;
    status.value = 'idle';
    error.value = null;
  };

  /**
   * 清空批改历史
   */
  const clearHistory = () => {
    history.value = [];
  };

  /**
   * 重置所有状态
   */
  const reset = () => {
    clearResult();
    clearHistory();
    loading.value = false;
  };

  // ==================== 返回 ====================

  return {
    // 状态
    correctionResult,
    history,
    loading,
    error,
    progress,
    status,

    // 计算属性
    isProcessing,
    hasResult,
    currentScore,
    errorCount,
    errorCategories,
    historyCount,

    // 操作
    submitForCorrection,
    getCorrectionResult,
    fetchHistory,
    clearResult,
    clearHistory,
    reset,
  };
});

